import { connect } from 'umi';
import { ContractManageAPI } from '../common/type';
import { ConractControllerContext, IContractsActionEnum, useContractsReducer } from '../common';
import { Form, Spin, message } from 'antd';
import { getMcontractByIDService, setOAMessageSev } from '../services';
import { DetailInfoTopViewOA } from './DetailInfoTopViewOA';
import { DetailInfoCenterViewOA } from './DetailInfoCenterViewOA';
import { DetailInfoBottomViewOA } from './DetailInfoBottomViewOA';
import { useEffect, useState } from 'react';
import { getColorTextLoadMap, getKeyRouter, getUserID, getPosIDs, getTenantID } from '@/utils';
import '../common/styles.less';
import { readReadShowFileService } from '@/services/BaseLayout';
import { ILoadMapTypeAll } from '@/common';

const DetailInfoViewOA: React.FC<ContractManageAPI.IContractDetailInfoView> = ({ curRes, locationProps }) => {
  /** 表单 */
  const [contractForm] = Form.useForm();

  /** 样式根名称 */
  const styleFixCls = 'contract-styfixcls-';

  /** 获取reducets */
  const { counterpartRows, contractTempRow, contractDispatch, partyFirstSelectRows } = useContractsReducer();

  /** 保存原合同信息 */
  const [saveOldContractInfo, setSaveOldContractInfo] = useState<Record<string, any>>({});

  /** 消息已读已办接口 */
  const { setOAMessageRun, setOAMessageLoaidng } = setOAMessageSev(() => {});

  /** 详情回调 */
  const detailsCallback = (res: any) => {
    if (res && res?.msgFlag) {
      // 做已读办理的接口处理
      let infoObject = res?.obj;
      if (infoObject && infoObject?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1007`]) {
        let workFlowNode = infoObject?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1007`];
        if (
          workFlowNode &&
          workFlowNode?.mactivitiTaskList?.length > 0 &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
        ) {
          // 已读未办
          setOAMessageRun({
            id: locationProps?.state?.taskId,
            isRemark: 0,
            viewType: 1,
          });
        }
      }

      contractDispatch({
        type: IContractsActionEnum.SELECT_COUNTERPARTROWS,
        payload: res?.obj?.oppositeList?.length > 0 ? res?.obj?.oppositeList : [],
      });

      contractDispatch({
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {},
      });

      // 处理合同主体信息
      contractDispatch({
        type: IContractsActionEnum.SELECT_PARTYALIST,
        payload: [
          {
            oppositeName: res?.obj?.oppositeName,
            oppositeID: res?.obj?.id,
            // phoneMobile: res?.obj?.contactMobile,
            // contactName: res?.obj?.contactName,
            creditID: res?.obj?.creditID,
            bankName: res?.obj?.bankName,
            bankAccount: res?.obj?.bankAccount,
            registerPhone: res?.obj?.registerPhone,
            workAddress: res?.obj?.workAddress,
            partyId: `party-first-${getKeyRouter()}`,
          },
        ],
      });
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情 */
  const { getMcontractByIDInfo, getMcontractByIDLoading, getMcontractByIDRun, reloadDetailInfo } = getMcontractByIDService(detailsCallback);

  /** 初始化 */
  useEffect(() => {
    if (locationProps?.state?.pageInfo?.id) {
      getMcontractByIDRun({
        id: locationProps?.state?.pageInfo?.id,
      });
    }

    if (locationProps?.state?.pIDDetailInfo?.id) {
      const infoObj: Record<string, any> = { ...locationProps?.state?.pIDDetailInfo };
      setSaveOldContractInfo(infoObj);
    }
  }, [locationProps?.state?.id]);

  /** 轻阅读预览 */
  const { readReadShowFileRun, readReadShowFileLoading } = readReadShowFileService();

  return (
    <ConractControllerContext.Provider
      value={{
        styleFixCls,
        curRes,
        locationID: locationProps?.state?.id,
        contractDispatch,
        pageType: locationProps?.state?.pageType,
        counterpartRows,
        contractTempRow,
        materialCheckRows: [],
        contractForm,
        contractDetailInfo: {
          ...getMcontractByIDInfo,
          supplyTypeName: getColorTextLoadMap(getMcontractByIDInfo?.supplyTypeName)?.colorText,
          procureRealName: getColorTextLoadMap(getMcontractByIDInfo?.procureRealName)?.colorText,
        },
        contarctJsonList: {},
        reloadDetail: reloadDetailInfo,
        updteAddOrEdit: {
          addContractRun: () => {},
          editContractRun: () => {},
          editRecordContractRun: () => {},
          submitRecordContractRun: () => {},
          addContractAttachRun: () => {},
          addAndSubmitContractRun: () => {},
        },
        oldContractForm: {},
        oldContractInfo: {
          ...saveOldContractInfo,
        },
        locationState: locationProps?.state,
        getDetailInfoRun: getMcontractByIDRun,
        partyFirstSelectRows,
        readReadShowFileRun,
        setOAMessageRun,
        taskId: locationProps?.state?.taskId,
        locationProps,
      }}
    >
      <Spin spinning={getMcontractByIDLoading || readReadShowFileLoading}>
        <div className={`${styleFixCls}infoViewOA`} id={'contract_oa_page'}>
          <DetailInfoTopViewOA />
          <DetailInfoCenterViewOA />
          <DetailInfoBottomViewOA />
        </div>
      </Spin>
    </ConractControllerContext.Provider>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(DetailInfoViewOA);
